<?php

class loginModel extends commonModel {
    /*
     *  $this->initialDB()
     *  Use $this->db to use function  to get mysql
     */

    public function __construct() {
        $this->initialDB();
    }

    
     public function loginCheck($account, $pwd) {
         
        $total=$this->getTotalCount('supervisor', '', '');
        
        if ($total == 0) {
            //沒有任何管理者  
            $result=$this->getAllByPage(1, 10, '', 'systemallows', '',array('id'=>'asc')); 
            if (count($result)==0) {
                //新建群組
                $permission = '';
                $index = 0;
                foreach (Data::$_au[1] as $value) {
                    if (is_array($value[3]) && count($value[3]) > 0) {
                        $index2 = 0;
                        foreach ($value[3] as $value2) {
                            $permission .= '1_' . $index . '_' . $index2 . ' ';
                            $index2++;
                        }
                    }
                    $permission .= '1_' . $index . ' ';
                    $index++;
                }
                $field_group = null;
                $field_group['name'] = '系統管理者';
                $field_group['permission'] = $permission;
                $field_group['createdt'] = 'now()';
                $field_group['updatedt'] = 'now()';
                $field_group['status'] = '1';
                $field_group['isdeleted'] = '0';
                $rows = $this->addItem($field_group, 'systemallows');  
                $sa_id = $rows;
            } else {
                $sa_id = $result[0]["id"];
            }

            //新建
            $salt = Data::getSalt(20);
            $saltpwd = sha1($salt . $pwd);
            $field = null;
            $field['account'] = $account;
            $field["said"] = $sa_id;
            $field['password'] = $saltpwd;
            $field['salt'] = $salt;
            //$field['name'] = 'admin';
            //$field['email'] = 'admin@admin.com';
            $field['createdt'] = 'now()';
            $field['updatedt'] = 'now()';
            $field['status'] = '1';
            $field['isdeleted'] = '0';

            $this->addItem($field, 'supervisor');

        }

        //回传admin验证
        $where = array("AND" => array("=" => array('account' => $account,'isdeleted'=>0)));
        $result=$this->getItemByCol($where, 'supervisor');
         
        return $result;
    }
    
}